<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title="isAdd ? '新增' : (isView ? '详情' : '编辑')" width="940px">
    <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="125px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发起时间">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
              style="width: 300px"
              :disabled="isView"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-select v-model="form.customerName" default-first-option placeholder="请选择客户" :disabled="isView" class="input_text" @change="handleSelect($event)">
              <el-option v-for="(item,index) in customerItem" :key="item.id + index" :label="item.customerName" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="任务名称" prop="taskTitle">
            <el-input v-model="form.taskTitle" class="row_length" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="任务内容" prop="taskContent">
            <el-input v-model="form.taskContent" class="row_length" :rows="4" type="textarea" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务地区" prop="province">
            <AreaSelect ref="areaSelect" :default-props="form" :disabled="isView" @change="handleSelectArea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="taskAddr">
            <el-input v-model="form.taskAddr" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="linker">
            <el-input v-model="form.linker" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="cellphone">
            <el-input v-model="form.cellphone" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="要求到场时间">
            <el-date-picker
              v-model="form.arriveTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
              style="width: 300px"
              :disabled="isView"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="要求完成时间">
            <el-date-picker
              v-model="form.finishTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
              style="width: 300px"
              :disabled="isView"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              :before-remove="handleBeforeRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-preview="handlePreview"
              :file-list="fileList"
              :headers="headers"
              :action="imagesUploadApi"
              class="upload-demo"
              multiple
              :disabled="isView"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" style="display: block;" class="el-upload__tip">请勿上传违法文件，且文件不超过15M</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.notes" class="row_length" rows="4" type="textarea" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="form.state !== 100" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="form.state === 100" type="text" @click="cancel">取消</el-button>
      <el-button v-show="form.state === 100" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, edit } from '@/api/tTasks'
import { mapGetters } from 'vuex'
import { del } from '@/api/picture'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
import AreaSelect from '@/components/AreaSelect'
import request from '@/utils/request'
import { isvalidPhone } from '@/utils/validate'

export default {
  components: {
    AreaSelect
  },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }

    return {
      customerItem: [],
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      dialogImageUrl: '',
      timeDefaultShow: new Date(),
      dialogVisible: false,
      fileList: [],
      loading: false, dialog: false,
      form: {
        id: '',
        taskTitle: '',
        taskContent: '',
        taskAddr: '',
        attachments: '',
        arriveTime: parseTime(new Date().getTime()),
        finishTime: parseTime(new Date().getTime()),
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        startTime: parseTime(new Date().getTime()),
        state: '',
        customerName: '',
        customerId: '',
        country: '',
        province: '',
        city: '',
        county: ''
      },
      rules: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        taskTitle: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        taskContent: [
          { required: true, message: '请输入任务内容', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择任务地区', trigger: 'blur' }
        ],
        taskAddr: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        faultDevices: [
          { required: true, message: '请选择报修设备', trigger: 'blur' }
        ],
        linker: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        startTime: [
          { required: true, message: '请输入发起时间', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  mounted() {
    this.tcustmerInfoAll()
  },
  methods: {
    tcustmerInfoAll() {
      request({
        url: 'api/tCustomerInfoAll',
        method: 'get'
      }).then(res => {
        this.customerItem = res
      })
    },
    handleSelect(item) {
      this.form.customerName = item.customerName
      this.form.customerId = item.id
    },
    handleSelectArea(countryItem, provinceItem, cityItem, areaItem) {
      this.form.country = countryItem.name
      this.form.province = provinceItem.name
      this.form.city = cityItem.name
      this.form.county = areaItem.name
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          const fileIds = []
          this.fileList.forEach(function(data, index) {
            fileIds.push(data.id)
          })
          this.form.attachments = fileIds.join(',')
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      this.form.startTime = parseTime(this.form.startTime)
      this.form.arriveTime = parseTime(this.form.arriveTime)
      this.form.finishTime = parseTime(this.form.finishTime)
      this.form.inputTime = this.form.inputTime === null ? this.form.inputTime : parseTime(this.form.inputTime)
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.supThis.init()
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },
    resetForm() {
      this.dialog = false
      this.fileList = []
      this.$refs['form'].resetFields()
      this.$refs['areaSelect'] && this.$refs['areaSelect'].clear()
      this.form = {
        id: '',
        taskTitle: '',
        taskContent: '',
        attachments: '',
        arriveTime: parseTime(new Date().getTime()),
        finishTime: parseTime(new Date().getTime()),
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        startTime: parseTime(new Date().getTime()),
        state: '',
        customerName: '',
        customerId: '',
        country: '',
        province: '',
        city: '',
        county: ''
      }
    },
    handlePreview(file) {
      window.open(file.url, '_blank')
    },
    handleSuccess(response, file, fileList) {
      const id = response.data[0]
      this.fileList.push({ name: id, id: id, url: '/api/picture/' + id })
      console.log(this.fileList)
    },
    handleBeforeRemove(file, fileList) {
      const _this = this
      for (let i = 0; i < _this.fileList.length; i++) {
        if (_this.fileList[i].id === file.name) {
          del(_this.fileList[i].id).then(res => {
            _this.fileList.splice(i, 1)
          })
        }
      }
      return true
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 刷新列表数据
    // doSubmit() {
    //   this.fileList = []
    //   this.dialogVisible = false
    //   this.dialogImageUrl = ''
    //   this.dialog = false
    //   this.$parent.$parent.init()
    // },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}
</script>

<style scoped>
.row_length {
    width: 760px
}
.input_text {
    width: 300px
}
</style>
